<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Admin\Controller;

use Admin\Data\Common;
use Doctrine\ORM\EntityManager;
use Laminas\Mvc\I18n\Translator;

class PaymentController extends AdminActionController
{
    private $translator;
    private $entityManager;

    public function __construct(
        Translator      $translator,
        EntityManager   $entityManager
    )
    {
        $this->translator       = $translator;
        $this->entityManager    = $entityManager;
    }

    /**
     * 支付列表
     * @return array|\Laminas\View\Model\ViewModel
     */
    public function indexAction()
    {
        $paymentArray   = Common::paymentList();

        return ['payment' => $paymentArray];
    }

    /**
     * 编辑支付
     * @return array|\Laminas\Http\Response
     */
    public function editAction()
    {
        $paymentName    = basename($this->params()->fromRoute('name', ''));
        $filePath       = 'data/moduleData/Payment/';
        $fileName       = ucfirst($paymentName) . '.php';
        if(!file_exists($filePath . $fileName)) return $this->adminCommon()->toReferer();

        $configArray= include $filePath . $fileName;
        $response   = $this->getEventManager()->trigger('admin-payment.edit.show', $this, ['configArray' => $configArray, 'paymentCode' => $paymentName]);
        $extend     = $response->last();
        if (isset($extend['paymentConfigState']) && $extend['paymentConfigState']) $configArray = $extend['configArray'];

        $service    = Common::getPaymentService($paymentName);

        if($this->getRequest()->isPost()) {
            $paymentArray = $this->request->getPost()->toArray();
            $service->savePaymentConfig($paymentArray, $configArray, $filePath . $fileName);
            $this->getEventManager()->trigger('admin-payment.edit.post', $this, ['paymentArray' => $paymentArray, 'configArray' => $configArray, 'paymentCode' => $paymentName]);

            $this->adminCommon()->addOperLog(sprintf($this->translator->translate('支付方式 %s 编辑成功!'), $paymentArray['paymentName']), $this->translator->translate('支付设置'));

            return $this->redirect()->toRoute('payment');
        }

        $paymentInput   = $service->getFormInput($configArray);

        return ['paymentCode' => $paymentName, 'formInput' => $paymentInput];
    }
}